package com.ihome.android.util.log;

import java.io.File;
import java.util.List;
import android.text.TextUtils;
import com.ihome.android.EAApp;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.util.FileUtils;
import com.ihome.android.util.SPMgr;
import com.ihome.android.util.TimeUtil;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;

public class UserBehaviorLog {

	public interface UserBehavior {
		final int	LOGIN							= 201;	//登录应用商店
		final int	LOGOUT							= 202;	//退出应用商店

		final int	CLICK_RECOMMAND_APP				= 210;	//应用推荐位点击行为
		final int	CLICK_RECOMMAND_ALBUM			= 211;	//专辑点击行为
		final int	CLICK_RECOMMAND_TOPIC			= 212;	//专题点击行为
		final int	CLICK_RECOMMAND_TOPIC_SPECIAL	= 213;	//“精选专题”点击行为
		final int	CLICK_RECOMMAND_RANK			= 214;	//“排行榜”点击行为

		final int	CLICK_ALBUM_APP					= 215;	//分类里面的应用点击行为

		final int	CLICK_APPMGR					= 216;	//“应用管理”点击行为
		final int	CLICK_SEARCH					= 217;	//搜索推荐位点击行为
		final int	CLICK_NAVI						= 218;	//导航栏目点击行为

		final int	CLICK_INSTALL					= 219;	//详情页应用安装点击行为
		final int	CLICK_FAVI_GUESS				= 220;	//详情页“猜你喜欢”点击行为
		final int	CLICK_OPEN						= 221;	//详情页 打开应用点击行为

		/**
		 * 
		 * 270：图片异常 <br>
		 * 271：应用下载异常<br>
		 * 272：应用升级异常<br>
		 * 273：应用打开异常<br>
		 * 274：商店页面访问异常<br>
		 * 275：搜索功能异常<br>
		 * 276：商店升级异常<br>
		 * 277：商店退出异常<br>
		 * 278：网络异常<br>
		 * 279：商店运行异常
		 */
		
		final int 	PICTURE_EXCEPTION 				= 270; //图片异常
		final int   APPDOWNLOAD_EXCEPTION			= 271; //应用下载异常
		final int   APPUPDATE_EXCEPTION				= 272; //应用升级异常
		final int   APPOPEN_EXCEPTION				= 273; //应用打开异常
		final int   STOREVISIT_EXCEPTION			= 274; //商店页面访问异常
		final int   SEARCHFUNCTION_EXCEPTION		= 275; //搜索功能异常
		final int   STOREUPDATE_EXCEPTION			= 276; //商店升级异常
		final int   STOREQUIT_EXCEPTION				= 277; //商店退出异常
		final int   NETWORK_EXCEPTION				= 278; //网络异常
		final int   STORERUN_EXCEPTION				= 279; //商店运行异常

	}

	/**
	 * 上报结果 0：正常成功行为上报 <br>
	 * 1：超时行为上报 <br>
	 * 2：失败行为上报（正常行为）<br>
	 * 3：异常行为上报（故障类）<br>
	 * 
	 */
	public interface NotifyType {
		final int	TYPE_NORMAL		= 0;	//0：正常成功行为上报
		final int	TYPE_TIMEOUT	= 1;	//1：超时行为上报
		final int	TYPE_FAILURE	= 2;	//2：失败行为上报（正常行为
		final int	TYPE_EXCEPTION	= 3;	//3：异常行为上报（故障类）
	}

	// MAC_统计周期起始时间_统计周期结束时间_周期时长_UserBehavior.log
	private String					mLogFileNameTemp;
	private String					mLogFileName;
	private String					mLogStartTime;
	private String					mLogStopTime;
	private static UserBehaviorLog	userBehaviorLog;
	private final String			TAG			= UserBehaviorLog.class.getSimpleName();

	private String					sessionKey	= "";

	public static UserBehaviorLog getInstance() {
		if (userBehaviorLog == null) {
			synchronized (UserBehaviorLog.class) {
				userBehaviorLog = new UserBehaviorLog();
			}
		}
		return userBehaviorLog;
	}

	private UserBehaviorLog() {
		initParams();
	}

	/**
	 * 初始化开始时间和临时日志文件
	 */
	private void initParams() {
		List<String> tempLogfiles = FileUtils.getTempLogFileList(ConfigUtil.LOG_PATH);
		if (tempLogfiles != null && tempLogfiles.size() > 0) {
			String logfile = tempLogfiles.get(0);
			mLogFileNameTemp = logfile.substring(logfile.lastIndexOf("/"), logfile.length());
			int startIndex = Util.getMac().length() + 2;
			mLogStartTime = mLogFileNameTemp.substring(startIndex, mLogFileNameTemp.length());
		}
		else {
			mLogStartTime = TimeUtil.getDefDate();
			mLogFileNameTemp = Util.getMac() + "_" + mLogStartTime;
		}
		LogUtil.v(TAG, " mTMLogStartTime = : " + mLogStartTime);
		LogUtil.v(TAG, " mTMLogFileNameTemp = : " + mLogFileNameTemp);

		sessionKey = TimeUtil.getDefDate() + Util.getMac();

		new Thread() {
			public void run() {
				List<String> logfiles = FileUtils.getLogFileList(ConfigUtil.LOG_PATH);
				if (logfiles != null && logfiles.size() > 0) {
					for (int i = 0, size = logfiles.size(); i < size; i++) {
						String filepath = logfiles.get(i);
						try {
							boolean uploadrslt = new HttpActions(EAApp.getApp()).fileUpload(filepath, "");
							if (uploadrslt) {
								LogUtil.v(TAG, " Upload file Successed ;  Log file.delete() is " + new File(filepath).delete());
							}
							else {
								LogUtil.v(TAG, " Upload file failure");
							}
						} catch (ITVException e) {
							e.printStackTrace();
						}
					}
				}

			};
		}.start();

	}

	/**
	 * 
	 * <一句话功能简述> <功能详细描述>
	 * 
	 * @param gatherType
	 * @param notifyType
	 *            上报结果 0：正常成功行为上报 <br>
	 *            1：超时行为上报 <br>
	 *            2：失败行为上报（正常行为）<br>
	 *            3：异常行为上报（故障类）<br>
	 * 
	 * 
	 * @param logs
	 * @see [类、类#方法、类#成员]
	 */
	public void writeLog(int gatherType, int notifyType, String description, String[] msg) {
		//LogUtil.v(TAG," writeLogAndUpload log--> \n" + logs);

		StringBuilder log = new StringBuilder();
		//gatherSource 采集来源标识，日志采集的业务来源，客户端填写“market”
		log.append("market").append("|");
		//SessionKey	开机会话ID，用户每次打开应用系统自动生成，生成规则：YYMMDDHHMMSS（开机系统时间）+MAC地址（无分隔符）
		log.append(sessionKey).append("|");
		//gatherType 行为上报类型： 101-200区间为桌面系统行为采集段；201-300区间为应用商城系统行为采集段；301-400区间为民生系统行为采集段；
		log.append(gatherType).append("|");
		//notifyType	上报结果
		log.append(notifyType).append("|");
		//MAC	终端MAC地址
		log.append(Util.getMac()).append("|");
		//templateCodes			机顶盒所支持的应用商店模板编码组成的字符串 
		log.append("004").append("|");
		//clientId	电信OTT平台终端号
		log.append(Util.getOTTClientID(EAApp.getApp())).append("|");
		//areaNo	区域编号
		log.append(SPMgr.getInstance(EAApp.getApp()).getElement(HttpKeys.KEY_AREANO, "320000")).append("|");
		//account	用户标识
		log.append(Util.getOTTUserName(EAApp.getApp())).append("|");
		//packageName	上报的应用包名
		log.append(EAApp.getApp().getPackageName()).append("|");
		//APKversion	上报的应用版本
		log.append(Util.getAPKVersion(EAApp.getApp())).append("|");
		//STBStartupTime	机顶盒开机时间，YYMMDDHHMMSS
		log.append(TimeUtil.getSTBStartupTime()).append("|");
		//timeStamp	上报时间，YYMMDDHHMMSS
		log.append(TimeUtil.getDefDate1()).append("|");
		//timeConsume	访问耗时（单位：毫秒）
		log.append("").append("|");
		//description	描述信息
		log.append(description).append("|");
		//Message1	上报信息字段
		log.append(msg.length > 0 ? msg[0] : "").append("|"); //position
		//Message2	上报信息字段
		log.append(msg.length > 1 ? msg[1] : "").append("|");//cid
		//Message3	上报信息字段
		log.append(msg.length > 2 ? msg[2] : "").append("|");
		//Message4	上报信息字段
		log.append(msg.length > 3 ? msg[3] : "").append("|");//appID
		//Message5	上报信息字段
		log.append(msg.length > 4 ? msg[4] : "").append("|");
		//Message6	上报信息字段
		log.append(msg.length > 5 ? msg[5] : "").append("|").append("\n");

		FileUtils.LogWrite2SD(EAApp.getApp(), log.toString(), mLogFileNameTemp);

		LogUtil.d(TAG, "(mLogFileNameTemp).length() =  " + new File(ConfigUtil.LOG_PATH + mLogFileNameTemp).length());
		int fileSize =256;
		if(!TextUtils.isEmpty(ConfigUtil.dataGatherSize)){
			fileSize = Integer.parseInt(ConfigUtil.dataGatherSize);
		}
		LogUtil.v(TAG, "uploadLog() --> fileSize==="+fileSize);
		if (new File(ConfigUtil.LOG_PATH + mLogFileNameTemp).length() >= fileSize * 1024) {
			uploadLog(true);
		}
	}

	public void uploadLog(boolean isretry) {
		LogUtil.v(TAG, "uploadLog() --> ");
		new Thread() {
			public void run() {
				try {
					mLogStopTime = TimeUtil.getDefDate();
					long duration = TimeUtil.getDurationTime(mLogStartTime);
					mLogStartTime = mLogStopTime;
					mLogFileName = mLogFileNameTemp + "_" + mLogStopTime + "_" + duration + "_UserBehavior.log";

					LogUtil.d(TAG, "  period upload mLogStopTime " + mLogStopTime + " mLogFileName: " + mLogFileName);

					File file = new File(ConfigUtil.LOG_PATH + mLogFileNameTemp);
					File tmfile = new File(ConfigUtil.LOG_PATH + mLogFileName);
					file.renameTo(tmfile);

					String filePath = tmfile.getAbsolutePath();
					LogUtil.v(TAG, " Upload file.getAbsolutePath(): " + filePath);
					for (int i = 0; i < 2; i++) {
						boolean uploadrslt = new HttpActions(EAApp.getApp()).fileUpload(filePath, "");
						if (uploadrslt) {
							LogUtil.v(TAG, " Upload file Successed ;  Log file.delete() is " + new File(filePath).delete());
							//重新记录
							mLogFileNameTemp = Util.getMac() + "_" + mLogStartTime;
							LogUtil.v(TAG, " Restart recording. mLogFileNameTemp = : " + mLogFileNameTemp);
							break;
						}
						else {
							LogUtil.v(TAG, " Upload file failure , try again! ");
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();

	}

}
